/*==============================================================================
案例2：客户细分分析 - 完整流程
================================================================================

业务场景：
某零售公司希望对客户进行细分，以便：
1. 制定差异化的营销策略
2. 优化产品推荐
3. 提高客户满意度和忠诚度

数据说明：
使用 Stata 内置的 auto.dta 数据集模拟客户购买行为
将汽车数据转换为客户消费数据

分析方法：
1. K-means 聚类识别客户群体
2. PCA 降维可视化
3. 客户画像分析
4. 营销策略建议

作者：Stata ML Course
日期：2025-11-03
==============================================================================*/

clear all
set more off
capture log close
log using "output/cases/case02_segmentation.log", replace

*------------------------------------------------------------------------------
* 1. 数据准备
*------------------------------------------------------------------------------

display "=" * 80
display "案例2：客户细分分析"
display "=" * 80
display ""

* 加载数据
sysuse auto, clear

display "原始数据概览："
describe
display "样本量: " _N

*------------------------------------------------------------------------------
* 2. 特征工程（模拟客户行为数据）
*------------------------------------------------------------------------------

display ""
display "特征工程：创建客户行为指标"
display "-" * 80

* 2.1 消费金额相关
gen purchase_amount = price
label variable purchase_amount "购买金额"

gen avg_transaction = price / (1 + int(runiform() * 5))
label variable avg_transaction "平均交易额"

* 2.2 购买频率
set seed 20251103
gen purchase_frequency = int(runiform() * 20) + 1
label variable purchase_frequency "购买频次（年）"

* 2.3 客户价值
gen customer_value = purchase_amount * purchase_frequency / 1000
label variable customer_value "客户年度价值（千元）"

* 2.4 产品偏好
gen product_preference = mpg
label variable product_preference "产品偏好得分"

* 2.5 品牌忠诚度
gen brand_loyalty = (foreign == 0) * 100 + runiform() * 50
label variable brand_loyalty "品牌忠诚度得分"

* 2.6 价格敏感度
gen price_sensitivity = 100 - (price / 100)
label variable price_sensitivity "价格敏感度"

* 2.7 购买力
gen purchasing_power = price / 1000
label variable purchasing_power "购买力指数"

*------------------------------------------------------------------------------
* 3. 数据标准化
*------------------------------------------------------------------------------

display ""
display "数据标准化"
display "-" * 80

* 选择用于聚类的变量
global cluster_vars "customer_value purchase_frequency avg_transaction ///
                     product_preference brand_loyalty price_sensitivity"

* 标准化
foreach var of global cluster_vars {
    egen `var'_mean = mean(`var')
    egen `var'_sd = sd(`var')
    gen `var'_std = (`var' - `var'_mean) / `var'_sd
    drop `var'_mean `var'_sd
}

*------------------------------------------------------------------------------
* 4. 确定最佳簇数（肘部法则）
*------------------------------------------------------------------------------

display ""
display "确定最佳簇数"
display "-" * 80

* 尝试不同的 k 值
forvalues k = 2/8 {
    quietly cluster kmeans customer_value_std purchase_frequency_std ///
        avg_transaction_std product_preference_std brand_loyalty_std ///
        price_sensitivity_std, k(`k') name(cluster_k`k') start(krandom) seed(20251103)
    
    display "K = `k' 完成"
}

display ""
display "建议：根据业务需求选择 k=4（四个客户群体）"

*------------------------------------------------------------------------------
* 5. K-means 聚类（k=4）
*------------------------------------------------------------------------------

display ""
display "K-means 聚类（k=4）"
display "=" * 80

cluster kmeans customer_value_std purchase_frequency_std avg_transaction_std ///
    product_preference_std brand_loyalty_std price_sensitivity_std, ///
    k(4) name(customer_segment) start(krandom) seed(20251103)

* 查看聚类结果
tab customer_segment

*------------------------------------------------------------------------------
* 6. 客户群体分析
*------------------------------------------------------------------------------

display ""
display "客户群体特征分析"
display "=" * 80

* 每个群体的统计特征
bysort customer_segment: summarize customer_value purchase_frequency ///
    avg_transaction product_preference brand_loyalty price_sensitivity

* 每个群体的大小
display ""
display "各客户群体规模："
tab customer_segment

*------------------------------------------------------------------------------
* 7. 客户画像命名
*------------------------------------------------------------------------------

display ""
display "客户画像命名"
display "-" * 80

* 根据特征给客户群体命名
gen segment_name = ""

* 分析每个群体的特征来命名
bysort customer_segment: egen avg_value = mean(customer_value)
bysort customer_segment: egen avg_freq = mean(purchase_frequency)
bysort customer_segment: egen avg_loyalty = mean(brand_loyalty)

* 简化命名逻辑（实际应根据具体数据调整）
replace segment_name = "高价值忠诚客户" if customer_segment == 1
replace segment_name = "潜力增长客户" if customer_segment == 2
replace segment_name = "价格敏感客户" if customer_segment == 3
replace segment_name = "低频小额客户" if customer_segment == 4

* 显示命名结果
display ""
display "客户群体命名："
tab segment_name customer_segment

*------------------------------------------------------------------------------
* 8. PCA 降维可视化
*------------------------------------------------------------------------------

display ""
display "PCA 降维可视化"
display "=" * 80

* PCA 分析
pca customer_value_std purchase_frequency_std avg_transaction_std ///
    product_preference_std brand_loyalty_std price_sensitivity_std, ///
    components(2)

* 碎石图
screeplot, yline(1) title("PCA 碎石图") scheme(s2color)
graph export "output/cases/figures/case02_screeplot.png", replace

* 提取主成分
predict pc1 pc2

* 主成分得分图（按客户群体着色）
scatter pc2 pc1, mcolor(customer_segment) mlabel(segment_name) ///
    title("客户细分可视化（PCA）") ///
    xtitle("第一主成分") ytitle("第二主成分") ///
    legend(label(1 "群体1") label(2 "群体2") label(3 "群体3") label(4 "群体4")) ///
    scheme(s2color)
graph export "output/cases/figures/case02_pca_segments.png", replace

*------------------------------------------------------------------------------
* 9. 业务洞察可视化
*------------------------------------------------------------------------------

display ""
display "生成业务洞察图表"
display "-" * 80

* 9.1 客户群体规模
graph bar (count), over(segment_name) ///
    title("各客户群体规模") ///
    ytitle("客户数量") ///
    blabel(bar, format(%9.0f)) ///
    scheme(s2color)
graph export "output/cases/figures/case02_segment_size.png", replace

* 9.2 客户价值对比
graph bar (mean) customer_value, over(segment_name) ///
    title("各群体平均客户价值") ///
    ytitle("年度价值（千元）") ///
    blabel(bar, format(%9.1f)) ///
    scheme(s2color)
graph export "output/cases/figures/case02_segment_value.png", replace

* 9.3 购买频次对比
graph bar (mean) purchase_frequency, over(segment_name) ///
    title("各群体平均购买频次") ///
    ytitle("年购买次数") ///
    blabel(bar, format(%9.1f)) ///
    scheme(s2color)
graph export "output/cases/figures/case02_segment_frequency.png", replace

* 9.4 品牌忠诚度对比
graph bar (mean) brand_loyalty, over(segment_name) ///
    title("各群体品牌忠诚度") ///
    ytitle("忠诚度得分") ///
    blabel(bar, format(%9.1f)) ///
    scheme(s2color)
graph export "output/cases/figures/case02_segment_loyalty.png", replace

* 9.5 价格敏感度对比
graph bar (mean) price_sensitivity, over(segment_name) ///
    title("各群体价格敏感度") ///
    ytitle("敏感度得分") ///
    blabel(bar, format(%9.1f)) ///
    scheme(s2color)
graph export "output/cases/figures/case02_segment_price_sensitivity.png", replace

* 9.6 客户价值分布（箱线图）
graph box customer_value, over(segment_name) ///
    title("各群体客户价值分布") ///
    ytitle("客户价值（千元）") ///
    scheme(s2color)
graph export "output/cases/figures/case02_value_distribution.png", replace

* 9.7 雷达图数据准备（多维特征对比）
preserve
collapse (mean) customer_value purchase_frequency avg_transaction ///
    product_preference brand_loyalty price_sensitivity, by(segment_name)
list
restore

*------------------------------------------------------------------------------
* 10. 营销策略建议
*------------------------------------------------------------------------------

display ""
display "=" * 80
display "营销策略建议"
display "=" * 80
display ""

* 为每个群体生成策略
forvalues i = 1/4 {
    display "客户群体 `i'："
    
    preserve
    keep if customer_segment == `i'
    
    * 计算群体特征
    quietly summarize customer_value
    local avg_val = r(mean)
    quietly summarize purchase_frequency
    local avg_freq = r(mean)
    quietly summarize brand_loyalty
    local avg_loyal = r(mean)
    
    display "  - 平均客户价值: " %8.2f `avg_val' " 千元"
    display "  - 平均购买频次: " %6.1f `avg_freq' " 次/年"
    display "  - 平均忠诚度: " %6.1f `avg_loyal'
    
    * 策略建议
    if `i' == 1 {
        display "  策略: VIP服务、专属优惠、优先体验新品"
    }
    else if `i' == 2 {
        display "  策略: 增加互动、会员升级激励、交叉销售"
    }
    else if `i' == 3 {
        display "  策略: 促销活动、价格优惠、性价比产品推荐"
    }
    else if `i' == 4 {
        display "  策略: 激活营销、首单优惠、提高购买频次"
    }
    
    display ""
    restore
}

*------------------------------------------------------------------------------
* 11. 保存结果
*------------------------------------------------------------------------------

display ""
display "保存分析结果"
display "-" * 80

* 保存完整数据
save "data/cases/customer_segmentation_results.dta", replace

* 导出客户群体摘要
preserve
collapse (mean) customer_value purchase_frequency avg_transaction ///
    product_preference brand_loyalty price_sensitivity (count) n=customer_segment, ///
    by(segment_name)
export delimited "output/cases/case02_segment_summary.csv", replace
list
restore

* 导出客户列表（带群体标签）
preserve
keep customer_segment segment_name customer_value purchase_frequency ///
    brand_loyalty price_sensitivity
export delimited "output/cases/case02_customer_list.csv", replace
restore

display ""
display "=" * 80
display "客户细分分析完成！"
display "=" * 80
display ""
display "输出文件："
display "  - 数据: data/cases/customer_segmentation_results.dta"
display "  - 群体摘要: output/cases/case02_segment_summary.csv"
display "  - 客户列表: output/cases/case02_customer_list.csv"
display "  - 图表: output/cases/figures/case02_*.png (7个图表)"
display "  - 日志: output/cases/case02_segmentation.log"
display ""
display "关键发现："
display "  - 识别出4个不同的客户群体"
display "  - 每个群体有明显的特征差异"
display "  - 可针对性制定营销策略"

log close

